﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using SmartFramework.Core.Pages;
using SmartFramework.Core.Utils;

namespace SmartFramework.Core.Plugin.Pages {
	public class SmartHttpModule : IHttpModule {
		/*
		 *  IHttpModule会不止一次的被Init()，加上这个状态变量避免意外的初始化, 
		 *  IHttpModule和HttpApplication一起工作，而HttpApplication会创建多个实例，
		 *  每一个实例在任意时刻只处理一个请求。所以，
		 *  HttpApplication实例的个数代表了Asp.Net同时能处理的请求数量
		 * */
		static volatile bool mModuleInited; 
		static volatile bool mSFInited; //Smart Framework是否已经被初始化
		public void Dispose() {
				
		}

		public void Init(HttpApplication context)
		{
			context.BeginRequest += OnBeginRequest;
		}

		private void OnBeginRequest (object sender,EventArgs args)
		{
			if (mSFInited) {
				return;
			}

			lock (typeof(SmartHttpModule)) {
				// 无法在Init()方法中直接初始化，因为在Init()的执行时，context.Request, Server.MapPath()都不能访问，也就无法确定~/config目录
				if (!mSFInited) {
					var context = (HttpApplication)sender;
					FS.SetCurrentDirectory(context.Request.PhysicalApplicationPath);
					ViewStateUtil.Init(new ViewStateUtil(new TempFileUtil(SFSettings.GetViewStatePath())));
					mSFInited = true;
				}
			}
		}
	}
}
